package com.demo.autotest.controller;

import com.demo.autotest.common.exception.LoginException;
import com.demo.autotest.common.utils.JwtUtils;
import com.demo.autotest.database.domain.Permission;
import com.demo.autotest.database.domain.User;
import com.demo.autotest.database.mapper.PermissionMapper;
import com.demo.autotest.dto.UserDTO;
import com.demo.autotest.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController // 定义一个controller类
@RequestMapping("/autotest")
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private PermissionMapper permissionMapper;

    @PostMapping("/login")
    public UserDTO login(@RequestBody User user, HttpServletResponse response){    // response即接口响应的实例
        UserDTO u = userService.getUserByAccount(user.getAccount());
        if(u==null){
            throw new LoginException("用户名不存在");
        }
        if(!u.getPassword().equals(user.getPassword())){
            throw new LoginException("密码不正确");
        }
        String token = JwtUtils.createPlatformToken(u);
        response.addHeader("token", token);
        // 返回用户在当前项目下的权限列表
        List<String> permissions = permissionMapper.getPermissionByProjectAndUser(u.getLastProject(), u.getId());
        u.setPermissions(permissions);
        u.setPassword(null);
        return u;
    }

}
